#include <iostream>
#include <pthread.h>
#include <queue>
const int defaultcap = 5; // for test

template <class T>
class BlockQueue
{
private:
    bool Full()
    {
        return _q.size() >= _capacity;
    }
    bool Empty()
    {
        return _q.empty();
    }

public:
    BlockQueue(int capacity=defaultcap)
        : _capacity(capacity), _sleep_Producer(0), _sleep_Consumer(0)
    {
        pthread_cond_init(&_product_cond, nullptr);
        pthread_cond_init(&_consum_cond, nullptr);
        pthread_mutex_init(&_mutex, nullptr);
    }
    void Equeue(T &data) // 生产者的接口
    {
        pthread_mutex_lock(&_mutex);
        
        while (Full())
        {
            _sleep_Producer++;
            pthread_cond_wait(&_product_cond, &_mutex);
            _sleep_Producer--;
        }
        // 生产
        
        _q.push(data);
        if (_sleep_Consumer > 0)
            pthread_cond_signal(&_consum_cond);
        pthread_mutex_unlock(&_mutex);
    }
    T Pop() // 消费者的接口
    {
        pthread_mutex_lock(&_mutex);
        while (Empty())
        {
            _sleep_Consumer++;
            
            pthread_cond_wait(&_consum_cond, &_mutex);
            _sleep_Consumer--;
        }
        T ret = _q.front();
        _q.pop();
        if (_sleep_Producer > 0)
            pthread_cond_signal(&_product_cond);
        pthread_mutex_unlock(&_mutex);
        return ret;
    }
    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_product_cond);
        pthread_cond_destroy(&_consum_cond);
    }

private:
    std::queue<T> _q;
    int _capacity;
    pthread_mutex_t _mutex;
    pthread_cond_t _product_cond;  // 掌管生产者睡觉的变量
    pthread_cond_t _consum_cond; // 掌管消费者睡觉的变量

    int _sleep_Producer; // 生产者
    int _sleep_Consumer; // 消费者
};